#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @Time    : 2018/1/24 15:17
# @Author  : RNone
import json
from json.decoder import JSONDecodeError
import logging
import requests

from api.api_base import api_base


class login(api_base):
	def do_login(self, caseDict):
		'''快速登陆，并保存cookies信息至本地'''
		session = requests.Session()
		host = 'http://' + caseDict['host']
		r = session.get(url=host)
		verify = self.find_verify(r.text)  # 获取页面verify
		loginData = {
			'LoginId': 'admin',
			'Password': 'admin123456!',
			'__RequestVerificationToken': verify
		}
		logging.debug('登陆VDA系统')
		r = session.post(url=host + '/Authentication/Login', data=loginData)
		return session

	def test_login(self, caseDict):
		'''登陆测试'''
		session = requests.Session()
		host = 'http://' + caseDict['host']
		r = session.get(url=host)
		verify = self.find_verify(r.text)
		loginData = caseDict['params']
		loginData['__RequestVerificationToken'] = verify
		logging.debug('发送登陆测试数据')
		r = session.post(url=host + '/Authentication/Login', data=loginData)
		try:
			data = json.loads(r.text)
		except JSONDecodeError as e:
			self.write_error(e)
			data = r.text
		caseDict['response'] = data
		result = self.login_result(r.cookies)
		if caseDict['expect'] == result:
			caseDict['result'] = 'PASS'
		else:
			caseDict['result'] = 'FAIL'
		return caseDict

	def login_result(self, cookies):
		'''登陆结果校验'''
		logging.debug('校验登陆结果')
		if 'VdaIIUser' in cookies:
			return 'succ'
		else:
			return 'fail'


if __name__ == '__main__':
	params = {'host': '192.168.60.186', 'user': 'admin', 'passwd': 'admin123456!'}
	lg = login()
	# lg.login_test(params)
	lg.do_login(params)
